package com.zl.console.common.config.filter;

import java.nio.charset.Charset;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import cn.hutool.core.net.URLDecoder;
import lombok.extern.slf4j.Slf4j;


/**
 * 简易登录验证 */
@Component
@Slf4j
public class AuthInfoInterceptor implements HandlerInterceptor {
    
    @Value("${console.loginKeys:autocode}")
    private String loginKeys;
    @Value("${console.loginCheck:true}")
    private boolean loginCheck;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(loginCheck){
            String token = request.getHeader("myToken");
            token = token!=null?token:request.getParameter("myToken");
            String requestedWith = request.getHeader("x-requested-with");
            boolean ajaxFlag = requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest");
            if(StringUtils.isBlank(token) || (!loginKeys.equals(token) 
                    && !loginKeys.equals(URLDecoder.decode(token, Charset.forName("UTF-8"))))){
                System.out.println(request.getServletPath());
                log.info("请求token失效>>{}", token);
                response.setStatus(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED.ordinal());
                return false;
            }
        }
        return true;//注意 这里必须是true否则请求将就此终止。
    }
 
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        
    }
}